import { useMemberStore } from '@/stores'

const baseURL = 'https://mall.ffhome.top/api'

const httpInterceptor = {
  invoke(options: UniApp.RequestOptions) {
    // 拼接请求地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    // 设置请求超时时间为10秒
    options.timeout = 10000
    // 添加小程序端请求头标识
    options.header = {
      ...options.header,
      token: 'test-mall',
    }
    // 添加token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
  code: number
  msg: string
  data: T
}

/**
 * 请求函数
 * @param UniApp.RequestOptions
 * @returns Promise
 */
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      success(res) {
        const info = res.data as Data<T>
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if (info.code === 0) {
            resolve(info)
          } else if (info.code === -2) {
            // 清理用户信息，跳转到登陆页
            const memberStore = useMemberStore()
            memberStore.clearProfile()
            uni.navigateTo({ url: '/pages/login/login' })
            reject(res)
          } else {
            // 其他错误
            uni.showToast({ icon: 'none', title: info.msg || '请求错误' })
            reject(res)
          }
        } else {
          // 其他错误
          uni.showToast({ icon: 'none', title: info.msg || '请求错误' })
          reject(res)
        }
      },
      fail(err) {
        uni.showToast({ icon: 'none', title: '网络错误，换个网络试试' })
        reject(err)
      },
    })
  })
}
